﻿using OnlineQC.CommomControl;
using OnlineQC.CommomControl.CommonForms;
using OnlineQC.CommomModule;
using OnlineQC.Globalization;
using OnlineQC.Model;
using OnlineQC.Model.Enum;
using OnlineQC.SubForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using static DevExpress.XtraEditors.Mask.MaskSettings;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace OnlineQC.PageUserControls
{
    public partial class SettedUserControl : ucBaseControl
    {
        private  List<DeviceInformation> deviceInformations = new List<DeviceInformation>();

        private EnumInterfaceType enumInterfaceType = EnumInterfaceType.USB;
        public SettedUserControl()
        {
            InitializeComponent();
        }
        private void SettedUserControl_Load(object sender, EventArgs e)
        {
            InitControl();

            SetControlStatus("init");
        }
        /// <summary>
        /// 初始化控件值
        /// </summary>
        private void InitControl()
        {
            rdoContectInfaceter.EditValue = 0;

            cmdMeasureTimeSpanUnit.Properties.DataSource = new List<DictionaryBase>() {
                new DictionaryBase(){ index=0,key=0,value="秒".ToMultiLanguage()},
                new DictionaryBase(){ index=1,key=1,value="毫秒".ToMultiLanguage()}
            };
            cmbFindDeviceSerialNumber.Properties.DataSource = new List<DictionaryBase>();
            cmdTriggerMode.Properties.DataSource = ObjectToModelHelper.EnumToDic(typeof(EnumTriggerMode));
            cmbLanguage.Properties.DataSource = new List<DictionaryBase>() { 
                new DictionaryBase(){ index=0,key=0,value="中文".ToMultiLanguage()},
                new DictionaryBase(){ index=1,key=1,value="英文".ToMultiLanguage()}
            };
            
            cmbScreen.Properties.DataSource = new List<DictionaryBase>() {
                new DictionaryBase(){ index=0,key=0,value="翻转".ToMultiLanguage()},
                new DictionaryBase(){ index=1,key=1,value="未翻转".ToMultiLanguage()}
            };
             
            cmd232BaudRate.Properties.DataSource = ParameterHelper.GetSupportBaudRate() ;
            cmd485BaudRate.Properties.DataSource = ParameterHelper.GetSupportBaudRate();


            cmblightSourceType.Properties.DataSource = ObjectToModelHelper.EnumToDic(typeof(EnumLightSource));
            cmbViewingAngle.Properties.DataSource = ObjectToModelHelper.EnumToDic(typeof(EnumAngle));

            cmbMeasureParameter.Properties.DataSource = ParameterHelper.GetParameterTypes();

        }
        #region 查找连接的仪器

        private void btnFindConnectDevice_Click(object sender, EventArgs e)
        {
            try
            {
                FrmShowHelper.ShowLoadingForm("正在获取仪器序列号...");
                enumInterfaceType = (EnumInterfaceType)rdoContectInfaceter.EditValue;
                int count = GlobalHelper.FindConnectDevices(enumInterfaceType, ref deviceInformations);

                if (count <= 0)
                {
                    FrmShowHelper.ShowMessage($"未找到连接仪器！");
                    return;
                }

                List<DictionaryBase> listDictionaryBase = new List<DictionaryBase>();
                for (int i = 0; i < deviceInformations.Count; i++)
                {
                    listDictionaryBase.Add(new DictionaryBase()
                    {
                        index = i,
                        key = i,
                        value = deviceInformations[i].DeviceSerialNumber,
                    });
                }

                cmbFindDeviceSerialNumber.Properties.DataSource = listDictionaryBase;
                if (listDictionaryBase.Count > 0)
                {
                    cmbFindDeviceSerialNumber.EditValue = listDictionaryBase[0].key;
                }
                cmbFindDeviceSerialNumber.Refresh();
                lbFindMessage.Text = string.Format($"找到{0}个仪器， 序列号如表格所示 ，请选择一个仪器的序列号在本页面设置参数", deviceInformations.Count);
                //设置仪器状态
                SetControlStatus("find");
                FrmShowHelper.ShowMessage($"找到{count}台仪器");

            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
            finally {
                FrmShowHelper.CloseLoadingForm();
            }
        }
        /// <summary>
        /// 连接 选中的仪器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChooseSetTarger_Click(object sender, EventArgs e)
        {
            try
            {
                //校验
                DeviceInformation deviceInformation = CheckCommunication(out string msg);
                if (deviceInformation == null)
                {
                    FrmShowHelper.ShowMessage(msg);
                    return;
                }
                FrmShowHelper.ShowLoadingForm("正在获取参数...");
                DeviceParameter deviceParameter = GlobalHelper.GetDeviceParammeter(enumInterfaceType, deviceInformation);
                deviceInformation.DeviceParameter = deviceParameter;
                if (deviceParameter == null)
                {
                    FrmShowHelper.ShowMessage("获取参数失败！");
                    return;
                }

                SetControlValue(deviceParameter);
                SetControlStatus("choose");
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
            finally
            {
                FrmShowHelper.CloseLoadingForm();
            }
        }

        #endregion 查找连接的仪器

        #region 设置控件
        private void SetControlStatus(string status)
        {
            if (status == "init")
            {
                btnChooseSetTarger.Enabled = false;

                groupParameterType.Enabled = false;
            }
            else if (status == "find")
            {
                btnChooseSetTarger.Enabled = true;

                groupParameterType.Enabled = false;
            }
            else if(status == "choose")
            {
                btnChooseSetTarger.Enabled = true;

                groupParameterType.Enabled = true;
            }
        }

        private void SetControlValue(DeviceParameter deviceParameter)
        {
            txtMeasureTimeSpan.Text = (deviceParameter.MeasureTimeSpan/1000).ToString();
            cmdMeasureTimeSpanUnit.EditValue = 0;
            cmdTriggerMode.EditValue = deviceParameter.TriggerMode;
            cmbLanguage.EditValue = deviceParameter.DeviceLanguage;
            cmbScreen.EditValue = deviceParameter.DeviceScreenDirection;
            cmd232BaudRate.EditValue = deviceParameter.Port232BaudRateIndex;
            cmd485BaudRate.EditValue = deviceParameter.Port485BaudRateIndex;

            txtDeviceIPAddr.Text = deviceParameter.DeviceNetworkIPAddr;
            txtPCIPAddr.Text = deviceParameter.PCIPAddr;
            txtPCPort.Text = deviceParameter.PCIPAddrPort.ToString();
            txtInternalAlignmentTimeSpan.Text = deviceParameter.InternalAlignmentTimeSpan.ToString();
            txtInternalAlignmentIntervalCount.Text = deviceParameter.InternalAlignmentIntervalCount.ToString();

            cmblightSourceType.EditValue = deviceParameter.LightSourceType;
            cmbViewingAngle.EditValue = deviceParameter.ViewingAngle;
            SetControlCheck(deviceParameter.CommunicationInterfaceTypes);
            //txtMeasureParameter.EditValue = deviceParameter.parameterFormat.ParametersDescription;
            cmbMeasureParameter.EditValue = deviceParameter.ParameterNumber;

            rdoUsingPrassive.EditValue = deviceParameter.IsUsingFourToTwentymAOut;
            SetAnalogSignalCheck(deviceParameter);
            cmbAnalogSignal.EditValue = deviceParameter.FourToTwentymAOutIndex;
            txtFourmAFigure.Text = deviceParameter.FourmAFigure.ToString();
            txtTwentymAFigure.Text = deviceParameter.TwentymAFigure.ToString();
        }
        private DeviceParameter GetControlValue()
        {
            DeviceParameter deviceParameter = new DeviceParameter();
            deviceParameter.MeasureTimeSpan = Convert.ToInt32(txtMeasureTimeSpan.Text);
            if (cmdMeasureTimeSpanUnit.EditValue?.ToString() == "0")
            {
                deviceParameter.MeasureTimeSpan = Convert.ToInt32(txtMeasureTimeSpan.Text)  * 1000;
            }
            deviceParameter.TriggerMode = Convert.ToInt32(cmdTriggerMode.EditValue);
            deviceParameter.DeviceLanguage = Convert.ToInt32(cmbLanguage.EditValue);
            deviceParameter.DeviceScreenDirection = Convert.ToInt32(cmbScreen.EditValue);
            deviceParameter.Port232BaudRateIndex = Convert.ToInt32(cmd232BaudRate.EditValue);
            deviceParameter.Port485BaudRateIndex = Convert.ToInt32(cmd485BaudRate.EditValue);

            deviceParameter.DeviceNetworkIPAddr = txtDeviceIPAddr.Text;
            deviceParameter.PCIPAddr = txtPCIPAddr.Text;
            deviceParameter.PCIPAddrPort = Convert.ToInt32(txtPCPort.Text);
            deviceParameter.InternalAlignmentTimeSpan = Convert.ToInt32(txtInternalAlignmentTimeSpan.Text);
            deviceParameter.InternalAlignmentIntervalCount = Convert.ToInt32(txtInternalAlignmentIntervalCount.Text);


            deviceParameter.LightSourceType = Convert.ToInt32(cmdTriggerMode.EditValue);
            deviceParameter.ViewingAngle = Convert.ToInt32(cmbLanguage.EditValue);
            deviceParameter.CommunicationInterfaceType = GetControlCheck();
            deviceParameter.ParameterNumber = Convert.ToInt32(cmbMeasureParameter.EditValue);

            deviceParameter.IsUsingFourToTwentymAOut = Convert.ToInt32(rdoUsingPrassive.EditValue);
            deviceParameter.FourToTwentymAOutIndex = Convert.ToInt32(cmbAnalogSignal.EditValue);
            deviceParameter.FourmAFigure = Convert.ToInt32(txtFourmAFigure.EditValue);
            deviceParameter.TwentymAFigure = Convert.ToInt32(txtTwentymAFigure.EditValue);

            return deviceParameter;
        }

        private string GetControlCheck()
        {
            string value = "";
            if (chcRS232.Checked)
            {
                value += "1";
            }
            else {
                value += "0";
            }
            if (chcRS485.Checked)
            {
                value += "1";
            }
            else
            {
                value += "0";
            }
            if (chcNetWork.Checked)
            {
                value += "1";
            }
            else
            {
                value += "0";
            }
            if (chcAnalogSignal.Checked)
            {
                value += "1";
            }
            else
            {
                value += "0";
            }
            if (chcUSB.Checked)
            {
                value += "1";
            }
            else
            {
                value += "0";
            }
            return value.PadRight(8,'0');
        }
        private void SetControlCheck(List<EnumInterfaceType> CommunicationInterfaceTypes)
        {
            chcUSB.Checked = false;
            chcRS232.Checked = false;
            chcRS485.Checked = false;
            chcNetWork.Checked = false;
            chcAnalogSignal.Checked = false;
            if (CommunicationInterfaceTypes.Contains(EnumInterfaceType.USB))
            {
                chcUSB.Checked = true;
            }
            if (CommunicationInterfaceTypes.Contains(EnumInterfaceType.RS232))
            {
                chcRS232.Checked = true;
            }
            if (CommunicationInterfaceTypes.Contains(EnumInterfaceType.RS485))
            {
                chcRS485.Checked = true;
            }
            if (CommunicationInterfaceTypes.Contains(EnumInterfaceType.NetworkInterface))
            {
                chcNetWork.Checked = true;
            }
            if (CommunicationInterfaceTypes.Contains(EnumInterfaceType.AnalogSignal))
            {
                chcAnalogSignal.Checked = true;
            }
        }

        /// <summary>
        /// 模拟信号参数
        /// </summary>
        /// <param name="CommunicationInterfaceTypes"></param>
        private void SetAnalogSignalCheck(DeviceParameter deviceParameter)
        {
            List<DictionaryBase> lisDictionaryBase = new List<DictionaryBase>();
            for (int i = 0; i < deviceParameter.parameterFormat.ChildParameterCount; i++)
            {
                lisDictionaryBase.Add(new DictionaryBase() {
                    index = i,
                    key = i,
                    value = deviceParameter.parameterFormat.ChildParameterNames[i]
                }) ;
            }
            cmbAnalogSignal.Properties.DataSource = lisDictionaryBase;
            cmbAnalogSignal.EditValue = lisDictionaryBase[0].key;
        }
        #endregion 设置控件
        #region 校验数据

       
        /// <summary>
        /// 发送指令前校验
        /// </summary>
        /// <param name="deviceSerialNumber"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private DeviceInformation CheckCommunication(out string msg)
        {
            msg = "";
            if (string.IsNullOrEmpty(cmbFindDeviceSerialNumber.EditValue?.ToString()))
            {
                msg = "仪器序列号为空!".ToMultiLanguage();
                return null;
            }
            string deviceSerialNumber =((DictionaryBase) cmbFindDeviceSerialNumber.GetSelectedDataRow()).value.ToString();
            DeviceInformation deviceInformation = deviceInformations.Find(o => o.DeviceSerialNumber == deviceSerialNumber);
            if (deviceInformation == null)
            {
                msg = "未初始化改仪器通信信息!".ToMultiLanguage();
                return null;
            }

            return deviceInformation;
        }

        /// <summary>
        /// 校验数据
        /// </summary>
        /// <returns></returns>
        private bool ParameterControlCheck(out string msg)
        {
            try
            {
                msg = "";

                string content = txtMeasureTimeSpan.EditValue?.ToString();
                if (string.IsNullOrEmpty(content))
                {
                    msg += "主动模式测量时间间隔输入不能!".ToMultiLanguage() + "\r\n";
                }
                int t = Convert.ToInt32(content);
                if (cmdMeasureTimeSpanUnit.EditValue?.ToString() == "0")
                {
                    t = t * 1000;
                }
                if (t < 1000)
                {
                    msg += "主动模式测量时间间隔不能不能小于1秒!".ToMultiLanguage() + "\r\n";
                }
                content = txtDeviceIPAddr.EditValue?.ToString();
                if (!IPCheck(content, out string m1))
                {
                    msg += "仪器的".ToMultiLanguage() + m1 + "\r\n";
                }
                content = txtPCIPAddr.EditValue?.ToString();
                if (!IPCheck(content, out string m2))
                {
                    msg += "PC的".ToMultiLanguage() + m2 + "\r\n";
                }
                content = txtPCPort.EditValue?.ToString();
                if (string.IsNullOrEmpty(content))
                {
                    msg += "端口号不能为空!".ToMultiLanguage() + "\r\n";
                }
                content = txtInternalAlignmentTimeSpan.EditValue?.ToString();
                if (string.IsNullOrEmpty(content))
                {
                    msg += "主动模式内部校准间隔时间不能为空!".ToMultiLanguage() + "\r\n";
                }
                content = txtInternalAlignmentIntervalCount.EditValue?.ToString();
                if (string.IsNullOrEmpty(content))
                {
                    msg += "主动模式内部校准间隔次数不能为空!".ToMultiLanguage() + "\r\n";
                }
                content = txtFourmAFigure.EditValue?.ToString();
                if (string.IsNullOrEmpty(content))
                {
                    msg += "4mA对应的数字量不能为空!".ToMultiLanguage() + "\r\n";
                }
                content = txtTwentymAFigure.EditValue?.ToString();
                if (string.IsNullOrEmpty(content))
                {
                    msg += "20mA对应的数字量不能为空!".ToMultiLanguage() + "\r\n";
                }
                if (!string.IsNullOrEmpty(msg))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
        }
        private bool IPCheck(string ip, out string msg)
        {
            msg = "";
            if (string.IsNullOrEmpty(ip))
            {
                msg = "IP地址格式不正确!例：127.0.0.0".ToMultiLanguage();
                return false;
            }
            string[] ipFormat = ip.Split('.');
            if (ipFormat.Length <4)
            {
                msg = "IP地址格式不正确!例：127.0.0.0".ToMultiLanguage();
                return false;
            }
            foreach ( string s in ipFormat)
            {
                if (string.IsNullOrEmpty(s))
                {
                    msg = "IP地址格式不正确!例：127.0.0.0".ToMultiLanguage();
                    return false;
                }
                if (Convert.ToInt32(s)>255)
                {
                    msg = "IP地址格式不正确!例：127.0.0.0,(.)联测的值不能大于255".ToMultiLanguage();
                    return false;
                }
            }
            return true;
        }
        #endregion 校验数据

        #region 界面操作
        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetParameter_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ParameterControlCheck(out string m))
                {
                    FrmShowHelper.ShowMessage(m);
                    return;
                }
                //获取控件值
                DeviceParameter deviceParameter = GetControlValue();
                //校验 接口信息
                DeviceInformation deviceInformation = CheckCommunication(out string msg);
                if (deviceInformation == null)
                {
                    FrmShowHelper.ShowMessage(msg);
                    return;
                }
                FrmShowHelper.ShowLoadingForm("正在设置参数...");
                if (!GlobalHelper.SetDeviceParammeter(enumInterfaceType, deviceInformation, deviceParameter))
                {
                    FrmShowHelper.ShowMessage("设置失败！".ToMultiLanguage());
                    return;
                }
                FrmShowHelper.ShowMessage("设置成功！".ToMultiLanguage());
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
            finally
            {
                FrmShowHelper.CloseLoadingForm();
            }
        }
        /// <summary>
        /// 内部校准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInternalAlignment_Click(object sender, EventArgs e)
        {
            try
            {
                //校验 接口信息
                DeviceInformation deviceInformation = CheckCommunication(out string msg);
                if (deviceInformation == null)
                {
                    FrmShowHelper.ShowMessage(msg);
                    return;
                }
                FrmShowHelper.ShowLoadingForm("正在内部校准...");
                if (!GlobalHelper.DeviceAlignment_Internal(enumInterfaceType, deviceInformation))
                {
                    FrmShowHelper.ShowMessage("内部校准成功！".ToMultiLanguage());
                    return;
                }
                FrmShowHelper.ShowMessage("内部校准成功！".ToMultiLanguage());
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
            finally
            {
                FrmShowHelper.CloseLoadingForm();
            }
        }
        /// <summary>
        /// 外部 白校准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExternalWhiteAlignment_Click(object sender, EventArgs e)
        {
            try
            {
                //校验 接口信息
                DeviceInformation deviceInformation = CheckCommunication(out string msg);
                if (deviceInformation == null)
                {
                    FrmShowHelper.ShowMessage(msg);
                    return;
                }
                FrmShowHelper.ShowLoadingForm("正在外部白校准...");
                if (!GlobalHelper.DeviceWhiteAlignment(enumInterfaceType, deviceInformation))
                {
                    FrmShowHelper.ShowMessage("外部白校准成功！".ToMultiLanguage());
                    return;
                }
                FrmShowHelper.ShowMessage("外部白校准成功！".ToMultiLanguage());
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
            finally
            {
                FrmShowHelper.CloseLoadingForm();
            }
        }
        /// <summary>
        /// 外部黑校准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExternalBlackAlignment_Click(object sender, EventArgs e)
        {
            try
            {
                //校验 接口信息
                DeviceInformation deviceInformation = CheckCommunication(out string msg);
                if (deviceInformation == null)
                {
                    FrmShowHelper.ShowMessage(msg);
                    return;
                }
                FrmShowHelper.ShowLoadingForm("正在外部黑校准...");
                if (!GlobalHelper.DeviceBlackAlignment(enumInterfaceType, deviceInformation))
                {
                    FrmShowHelper.ShowMessage("外部黑校准成功！".ToMultiLanguage());
                    return;
                }
                FrmShowHelper.ShowMessage("外部黑校准成功！".ToMultiLanguage());
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
            finally
            {
                FrmShowHelper.CloseLoadingForm();
            }
        }
        #endregion 界面操作

        #region 本地配置文件
        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadConfigParameter_Click(object sender, EventArgs e)
        {
            try
            {
                DeviceParameter deviceParameter = ReadDeviceParameter();
                
                if (deviceParameter == null)
                {
                    MessageBox.Show("配置文件参数读取失败!".ToMultiLanguage());
                    return;
                }
                //设置控件
                SetControlValue(deviceParameter);

                MessageBox.Show("配置文件参数读取成功!".ToMultiLanguage());
                
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
        }
        /// <summary>
        /// 保存参数配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveConfigParameter_Click(object sender, EventArgs e)
        {
            try
            {
                DeviceParameter deviceParameter = GetControlValue();

                if (!SaveDeviceParameter(deviceParameter,out string msg))
                {
                    MessageBox.Show(msg);
                    return;
                }
                MessageBox.Show("配置文件参数设置成功!".ToMultiLanguage());

            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
            }
        }
        /// <summary>
        /// 读取默认参数
        /// </summary>
        /// <returns></returns>
        public DeviceParameter ReadDeviceParameter()
        {
            try
            {
                DeviceParameter deviceParameter = new DeviceParameter();
                XmlDocument xml = new XmlDocument();
                //获取应用的当前路径
                if (!FileHelper.FileExists(Global.applicationSetting.DefaultParameterPath, Global.applicationSetting.DefaultParameterName))
                {
                    if (CreateParameterFile(deviceParameter, Global.applicationSetting.DefaultParameterPathName))
                    {
                        return deviceParameter;
                    }
                    else {
                        throw new Exception("新增参数配置文件异常！");
                    }
                }
                //加载xml文件
                xml.Load(Global.applicationSetting.DefaultParameterPathName);
                XmlElement xnode_root = (XmlElement)xml.SelectSingleNode("root");
                XmlElement xnode = (XmlElement)xnode_root.SelectSingleNode("DeviceParameter");
                {
                    deviceParameter.MeasureTimeSpan = int.Parse(xnode.SelectSingleNode("MeasureTimeSpan").InnerText.ToString());
                    deviceParameter.TriggerMode = int.Parse(xnode.SelectSingleNode("TriggerMode").InnerText.ToString());
                    deviceParameter.CommunicationInterfaceType = xnode.SelectSingleNode("CommunicationInterfaceType").InnerText.ToString();
                    deviceParameter.ParameterNumber = int.Parse(xnode.SelectSingleNode("ParameterNumber").InnerText.ToString());
                    deviceParameter.FourToTwentymAOutIndex = int.Parse(xnode.SelectSingleNode("FourToTwentymAOutIndex").InnerText.ToString());
                    deviceParameter.FourmAFigure = int.Parse(xnode.SelectSingleNode("FourmAFigure").InnerText.ToString());
                    deviceParameter.TwentymAFigure = int.Parse(xnode.SelectSingleNode("TwentymAFigure").InnerText.ToString());
                    deviceParameter.LightSourceType = int.Parse(xnode.SelectSingleNode("LightSourceType").InnerText.ToString());
                    deviceParameter.ViewingAngle = int.Parse(xnode.SelectSingleNode("ViewingAngle").InnerText.ToString());
                    deviceParameter.DeviceNetworkIPAddr = xnode.SelectSingleNode("DeviceNetworkIPAddr").InnerText.ToString();
                    deviceParameter.PCIPAddr = xnode.SelectSingleNode("PCIPAddr").InnerText.ToString();
                    deviceParameter.PCIPAddrPort = int.Parse(xnode.SelectSingleNode("PCIPAddrPort").InnerText.ToString());
                    deviceParameter.InternalAlignmentTimeSpan = int.Parse(xnode.SelectSingleNode("InternalAlignmentTimeSpan").InnerText.ToString());
                    deviceParameter.InternalAlignmentIntervalCount = int.Parse(xnode.SelectSingleNode("InternalAlignmentIntervalCount").InnerText.ToString());
                    deviceParameter.DeviceLanguage = int.Parse(xnode.SelectSingleNode("DeviceLanguage").InnerText.ToString());
                    deviceParameter.DeviceScreenDirection = int.Parse(xnode.SelectSingleNode("DeviceScreenDirection").InnerText.ToString());
                    deviceParameter.Port232BaudRateIndex = int.Parse(xnode.SelectSingleNode("Port232BaudRateIndex").InnerText.ToString());
                    deviceParameter.Port485BaudRateIndex = int.Parse(xnode.SelectSingleNode("Port485BaudRateIndex").InnerText.ToString());
                }
                return deviceParameter;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
       
        /// <summary>
        /// 保存默认参数
        /// </summary>
        /// <returns></returns>
        public bool SaveDeviceParameter(DeviceParameter deviceParamater, out string msg)
        {
            msg = "";
            try
            {
                XmlDocument xml = new XmlDocument();
                //获取应用的当前路径
                if (!FileHelper.FileExists(Global.applicationSetting.DefaultParameterPath, Global.applicationSetting.DefaultParameterName))
                {
                    if (!CreateParameterFile(deviceParamater,Global.applicationSetting.DefaultParameterPathName))
                    {
                        return false;
                    }
                    return true;
                }
                //加载xml文件
                xml.Load(Global.applicationSetting.DefaultParameterPathName);
                XmlElement xnode_root = (XmlElement)xml.SelectSingleNode("root");
                XmlElement xnode = (XmlElement)xnode_root.SelectSingleNode("DeviceParameter");
                //foreach (XmlNode item in xnode.ChildNodes)
                {
                    xnode.SelectSingleNode("MeasureTimeSpan").InnerText = deviceParamater.MeasureTimeSpan.ToString();
                    xnode.SelectSingleNode("TriggerMode").InnerText = deviceParamater.TriggerMode.ToString();
                    xnode.SelectSingleNode("CommunicationInterfaceType").InnerText = deviceParamater.CommunicationInterfaceType.ToString();
                    xnode.SelectSingleNode("ParameterNumber").InnerText = deviceParamater.ParameterNumber.ToString();
                    xnode.SelectSingleNode("FourToTwentymAOutIndex").InnerText = deviceParamater.FourToTwentymAOutIndex.ToString();
                    xnode.SelectSingleNode("FourmAFigure").InnerText = deviceParamater.FourmAFigure.ToString();
                    xnode.SelectSingleNode("TwentymAFigure").InnerText = deviceParamater.TwentymAFigure.ToString();
                    xnode.SelectSingleNode("LightSourceType").InnerText = deviceParamater.LightSourceType.ToString();
                    xnode.SelectSingleNode("ViewingAngle").InnerText = deviceParamater.ViewingAngle.ToString();
                    xnode.SelectSingleNode("DeviceNetworkIPAddr").InnerText = deviceParamater.DeviceNetworkIPAddr.ToString();
                    xnode.SelectSingleNode("PCIPAddr").InnerText = deviceParamater.PCIPAddr.ToString();
                    xnode.SelectSingleNode("PCIPAddrPort").InnerText = deviceParamater.PCIPAddrPort.ToString();
                    xnode.SelectSingleNode("InternalAlignmentTimeSpan").InnerText = deviceParamater.InternalAlignmentTimeSpan.ToString();
                    xnode.SelectSingleNode("InternalAlignmentIntervalCount").InnerText = deviceParamater.InternalAlignmentIntervalCount.ToString();
                    xnode.SelectSingleNode("DeviceLanguage").InnerText = deviceParamater.DeviceLanguage.ToString();
                    xnode.SelectSingleNode("DeviceScreenDirection").InnerText = deviceParamater.DeviceScreenDirection.ToString();
                    xnode.SelectSingleNode("Port232BaudRateIndex").InnerText = deviceParamater.Port232BaudRateIndex.ToString();
                    xnode.SelectSingleNode("Port485BaudRateIndex").InnerText = deviceParamater.Port485BaudRateIndex.ToString();
                    }
                xml.Save(Global.applicationSetting.DefaultParameterPathName);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
        }
        private bool CreateParameterFile(DeviceParameter deviceParameter ,string fileName)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                XmlDeclaration dec = document.CreateXmlDeclaration("1.0", "utf-8", null);
                document.AppendChild(dec);
                XmlElement root = document.CreateElement("root");
                document.AppendChild(root);
                XmlElement parameter = document.CreateElement("DeviceParameter");
                root.AppendChild(parameter);

                XmlElement element1 = document.CreateElement("MeasureTimeSpan");
                element1.InnerText = deviceParameter.MeasureTimeSpan.ToString();
                parameter.AppendChild(element1);
                XmlElement element2 = document.CreateElement("TriggerMode");
                element2.InnerText = deviceParameter.TriggerMode.ToString();
                parameter.AppendChild(element2);
                XmlElement element3 = document.CreateElement("CommunicationInterfaceType");
                element3.InnerText = deviceParameter.CommunicationInterfaceType?.ToString();
                parameter.AppendChild(element3);
                XmlElement element4 = document.CreateElement("ParameterNumber");
                element4.InnerText = deviceParameter.ParameterNumber.ToString();
                parameter.AppendChild(element4);
                XmlElement element5 = document.CreateElement("FourToTwentymAOutIndex");
                element5.InnerText = deviceParameter.FourToTwentymAOutIndex.ToString();
                parameter.AppendChild(element5);
                XmlElement element6 = document.CreateElement("FourmAFigure");
                element6.InnerText = deviceParameter.FourmAFigure.ToString();
                parameter.AppendChild(element6);
                XmlElement element7 = document.CreateElement("TwentymAFigure");
                element7.InnerText = deviceParameter.TwentymAFigure.ToString();
                parameter.AppendChild(element7);
                XmlElement element8 = document.CreateElement("LightSourceType");
                element8.InnerText = deviceParameter.LightSourceType.ToString();
                parameter.AppendChild(element8);
                XmlElement element9 = document.CreateElement("ViewingAngle");
                element9.InnerText = deviceParameter.ViewingAngle.ToString();
                parameter.AppendChild(element9);
                XmlElement element10 = document.CreateElement("DeviceNetworkIPAddr");
                element10.InnerText = deviceParameter.DeviceNetworkIPAddr?.ToString();
                parameter.AppendChild(element10);
                XmlElement element11 = document.CreateElement("PCIPAddr");
                element11.InnerText = deviceParameter.PCIPAddr?.ToString();
                parameter.AppendChild(element11);
                XmlElement element12 = document.CreateElement("PCIPAddrPort");
                element12.InnerText = deviceParameter.PCIPAddrPort.ToString();
                parameter.AppendChild(element12);
                XmlElement element13 = document.CreateElement("InternalAlignmentTimeSpan");
                element13.InnerText = deviceParameter.InternalAlignmentTimeSpan.ToString();
                parameter.AppendChild(element13);
                XmlElement element14 = document.CreateElement("InternalAlignmentIntervalCount");
                element14.InnerText = deviceParameter.InternalAlignmentIntervalCount.ToString();
                parameter.AppendChild(element14);
                XmlElement element15 = document.CreateElement("DeviceLanguage");
                element15.InnerText = deviceParameter.DeviceLanguage.ToString();
                parameter.AppendChild(element15);
                XmlElement element16 = document.CreateElement("DeviceScreenDirection");
                element16.InnerText = deviceParameter.DeviceScreenDirection.ToString();
                parameter.AppendChild(element16);
                XmlElement element17 = document.CreateElement("Port232BaudRateIndex");
                element17.InnerText = deviceParameter.Port232BaudRateIndex.ToString();
                parameter.AppendChild(element17);
                XmlElement element18 = document.CreateElement("Port485BaudRateIndex");
                element18.InnerText = deviceParameter.Port485BaudRateIndex.ToString();
                parameter.AppendChild(element18);
                // 1 输出到文件
                document.Save(fileName);

                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #endregion 本地配置文件

        private void btnSelectMeasureParameter_Click(object sender, EventArgs e)
        {
            MeasureParameterFrm measureParameterFrm = new MeasureParameterFrm();
            FrmShowHelper.ShowDialogFrm(measureParameterFrm);
        }
    }
}
